<template>
    <div class="detail-container">
        <div style="margin-top: 20px">
            <el-steps :active="formatStepStatus(order.orderStatus)" finish-status="success" align-center>
                <el-step
                        v-for="(step, index) in steps"
                        :key="index"
                        :title="step.title"
                        :description="getDescription(index)"
                ></el-step>
            </el-steps>
        </div>
        <el-card shadow="never" style="margin-top: 15px">
<!--            <div class="operate-container">-->
<!--                <i class="el-icon-warning color-danger" style="margin-left: 20px"></i>-->
<!--                <span class="color-danger">当前订单状态：{{this.status[parseInt(order.orderStatus)-1]}}</span>-->
<!--                <div class="operate-button-container"-->
<!--                     v-show="order.orderStatus==='1' && role==='平台运营商' ">-->
<!--                    <el-button size="mini" @click="showCloseOrderDialog">取消订单</el-button>-->
<!--                    <el-button size="mini" @click="showSureOrderDialog">确认订单</el-button>-->
<!--                </div>-->

<!--              <div class="operate-button-container"-->
<!--                   v-show="order.orderStatus==='1' && role==='B端客户' ">-->
<!--                <el-button size="mini" @click="showSureOrderDialog">提交订单</el-button>-->
<!--              </div>-->

<!--                <div class="operate-button-container"-->
<!--                     v-show=" order.orderStatus==='2'||order.orderStatus==='3'|| order.orderStatus==='4'">-->
<!--                  <el-button type="primary" size="mini" @click="submitAllChanges">提交所有变更</el-button>-->
<!--                  <el-button size="mini" @click="showCloseOrderDialog">取消订单</el-button>-->
<!--                </div>-->


<!--                <div class="operate-button-container" v-show="order.orderStatus===9">-->
<!--                    <el-button size="mini" @click="showCloseOrderDialog">删除订单</el-button>-->
<!--                </div>-->
<!--            </div>-->
            <div style="margin-top: 20px">
                <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
                <span class="font-small">基本信息</span>
            </div>
            <div class="table-layout">
                <el-row>
                    <el-col :span="8" class="table-cell-title">订单编号</el-col>
                    <el-col :span="8" class="table-cell-title">创建时间</el-col>
                    <el-col :span="8" class="table-cell-title">客户名称</el-col>

                </el-row>
                <el-row>
                    <el-col :span="8" class="table-cell">{{order.orderId}}</el-col>
                    <el-col :span="8" class="table-cell">{{order.orderDate}}</el-col>
                    <el-col :span="8" class="table-cell">{{customer.customerName}}</el-col>

                </el-row>
                <el-row>
                  <el-col :span="8" class="table-cell-title">支付方式</el-col>
                  <el-col :span="8" class="table-cell-title">订单类型</el-col>
                    <el-col :span="8" class="table-cell-title">物流单号</el-col>

                </el-row>
                <el-row>
                  <el-col :span="8" class="table-cell">{{payment.dictLabel}}</el-col>
                  <el-col :span="8" class="table-cell">{{business.dictLabel}}</el-col>
                    <el-col :span="8" class="table-cell">{{orderTrace.logisticsNumber}}</el-col>

                </el-row>


            </div>

            <div style="margin-top: 20px; display: flex; align-items: center;">
                <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
                <span class="font-small">商品信息</span>
                <el-button  size="big" style="margin-left: auto;" @click="handleAddMer">
                    新增商品列表
                </el-button>
            </div>
            <el-table :data="enrichedOrderDetails" :span-method="objectSpanMethod" style="width: 100%;margin-top: 20px" border>
                <el-table-column prop="customerAddr" label="配送地址" width="400" align="center"></el-table-column>
                <el-table-column prop="productId" label="商品编码" width="180"></el-table-column>
                <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
<!--                <el-table-column prop="productCategory" label="商品类别" width="180"></el-table-column>-->
                <el-table-column prop="source" label="生产商" width="180"></el-table-column>
                <el-table-column prop="price" label="单价（元）" width="180">
                  <template #default="scope">
                    <span class="color-danger">{{parseFloat(scope.row.price).toFixed(2)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="productSalesQuantity" label="销售数量" width="180"></el-table-column>
                <el-table-column prop="totalAmount" label="小计（元）" width="180">
                  <template #default="scope">
                    <span class="color-danger">{{parseFloat(scope.row.totalAmount).toFixed(2)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="总金额（元）" width="180">
                  <template #default="scope">
                    <span class="color-danger">{{parseFloat(scope.row.totalAmount).toFixed(2)}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="warehouseCode" label="仓库编码" width="180"></el-table-column>
                <el-table-column prop="remark" label="备注" width="180"></el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
                    <template #default="scope">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                                   v-hasPermi="['system:order:edit']" >修改</el-button>
                      <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                                 v-hasPermi="['system:order:edit']" >删除</el-button>
                    </template>
                </el-table-column>


            </el-table>
            <div style="float: right;margin: 20px">
                合计：<span class="color-danger">￥{{order.orderTotal}}</span>
            </div>
            <div style="margin-top: 60px">
                <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
                <span class="font-small">费用信息</span>
            </div>
            <div class="table-layout" style="padding-bottom: 20px">
                <el-row>
                    <el-col :span="6" class="table-cell-title">商品合计</el-col>
                    <el-col :span="6" class="table-cell-title">运费</el-col>
                    <el-col :span="6" class="table-cell-title">优惠券</el-col>
                    <el-col :span="6" class="table-cell-title">积分抵扣</el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="table-cell">￥{{formatCurrency(order.orderTotal)}}</el-col>
                    <el-col :span="6" class="table-cell">￥{{formatCurrency()}}</el-col>
                    <el-col :span="6" class="table-cell">-￥{{formatCurrency()}}</el-col>
                    <el-col :span="6" class="table-cell">-￥{{formatCurrency()}} </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="table-cell-title">活动优惠</el-col>
                    <el-col :span="6" class="table-cell-title">折扣金额</el-col>
                    <el-col :span="6" class="table-cell-title">订单总金额</el-col>
                    <el-col :span="6" class="table-cell-title">应付款金额</el-col>
                </el-row>
              <el-row>
                <el-col :span="6" class="table-cell">-￥{{ formatCurrency(order.promotionAmount) }}</el-col>
                <el-col :span="6" class="table-cell">-￥{{ formatCurrency(order.discountAmount) }}</el-col>
                <el-col :span="6" class="table-cell">
                  <span class="color-danger">￥{{ formatCurrency(order.orderTotal) }}</span>
                </el-col>
                <el-col :span="6" class="table-cell" >
                  <span class="color-danger">￥{{ formatCurrency(order.orderTotal) }}</span>
                </el-col>
              </el-row>
            </div>

          <div style="margin-top: 60px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">发票信息</span>
          </div>

          <div style="margin-top: 20px; width: 100%">
            <image-upload
                v-model="order.invoiceInfo"
                :limit="5"
                :multiple="true"
                :file-type="['jpg','jpeg','png','pdf']"
            ></image-upload>
          </div>


          <!-- 修改底部按钮容器为flex布局 -->
          <div style="margin-top: 20px; display: flex; justify-content: center; gap: 10px; flex-wrap: wrap">
            <!-- 平台运营商操作 -->
            <div v-show="order.orderStatus==='1' && role==='平台运营商'">
              <el-button type="primary" size="mini" @click="showSureOrderDialog">确认订单</el-button>
              <el-button size="mini" @click="showCloseOrderDialog">取消订单</el-button>
            </div>

            <!-- B端客户操作 -->
            <div v-show="order.orderStatus==='1' && role==='B端客户'">
              <el-button type="primary" size="mini" @click="showSureOrderDialog">提交订单</el-button>
            </div>

            <!-- 订单状态2/3/4操作 -->
            <div v-show="order.orderStatus==='2'||order.orderStatus==='3'||order.orderStatus==='4'">
              <el-button type="primary" size="mini" @click="submitAllChanges">提交所有变更</el-button>
              <el-button size="mini" @click="showCloseOrderDialog">取消订单</el-button>
            </div>

            <!-- 已关闭订单操作 -->
            <div v-show="order.orderStatus===9">
              <el-button size="mini" @click="showCloseOrderDialog">删除订单</el-button>
            </div>

            <!-- 返回按钮 -->
            <div>
              <el-button @click="handleBack()">返 回</el-button>
            </div>
          </div>




          <!--<div style="margin-top: 20px">-->
            <!--<svg-icon icon-class="marker" style="color: #606266"></svg-icon>-->
            <!--<span class="font-small">操作信息</span>-->
            <!--</div>-->
            <!--<el-table style="margin-top: 20px;width: 100%"-->
            <!--ref="orderHistoryTable"-->
            <!--:data="order.historyList" border>-->
            <!--<el-table-column label="操作者"  width="120" align="center">-->
            <!--<template slot-scope="scope">-->
            <!--{{scope.row.operateMan}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="操作时间"  width="160" align="center">-->
            <!--<template slot-scope="scope">-->
            <!--{{formatTime(scope.row.createTime)}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="订单状态"  width="120" align="center">-->
            <!--<template slot-scope="scope">-->
            <!--{{scope.row.orderStatus | formatStatus}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="付款状态"  width="120" align="center">-->
            <!--<template slot-scope="scope">-->
            <!--{{scope.row.orderStatus | formatPayStatus}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="发货状态"  width="120" align="center">-->
            <!--<template slot-scope="scope">-->
            <!--{{scope.row.orderStatus | formatDeliverStatus}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="备注" align="center">-->
            <!--<template slot-scope="scope">-->
            <!--{{scope.row.note}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--</el-table>-->




        </el-card>





      <!-- 修改弹窗 -->
      <el-dialog title="修改商品详情" v-model="editdialogVisible" width="40%">
        <el-form :model="form"  ref="orderForm" label-width="120px">
          <el-form-item label="商品编码" prop="productId" style="width: 90%;">
            <el-input v-model="form.productId" disabled></el-input>
          </el-form-item>
          <el-form-item label="商品名称" prop="merchandiseName" style="width: 90%;">
            <el-input v-model="form.productName" disabled></el-input>
          </el-form-item>
          <el-form-item label="商品类别" prop="merchandiseCategory" style="width: 90%;">
            <el-input v-model="form.productCategory" disabled></el-input>
          </el-form-item>
          <el-form-item label="生产商" prop="manufacturer" style="width: 90%;">
            <el-input v-model="form.source" disabled></el-input>
          </el-form-item>
          <el-form-item label="单价" prop="productPrice" style="width: 90%;">
            <el-input v-model.number="form.price" disabled></el-input>
          </el-form-item>
          <el-form-item label="销售数量" prop="productSalesQuantity" style="width: 90%;">
            <el-input-number v-model="form.productSalesQuantity" @change="updateEditMertotal(form)"/>
          </el-form-item>
          <el-form-item label="小计" prop="subtotal" style="width: 90%;">
            <el-input v-model.number="form.totalAmount" disabled></el-input>
          </el-form-item>
          <el-form-item label="总金额" prop="totalAmount" style="width: 90%;">
            <el-input v-model.number="form.totalAmount" disabled></el-input>
          </el-form-item>
          <el-form-item label="仓库编码" prop="warehouseCode" style="width: 90%;">
            <el-input v-model="form.warehouseCode" disabled ></el-input>
          </el-form-item>
          <el-form-item label="配送地址" prop="customerAddr" style="width: 90%;">
            <el-input
                v-model="form.customerAddr"
                type="textarea"
                :rows="2"
                disabled
                placeholder="无地址信息">
            </el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark" style="width: 90%;">
            <el-input v-model="form.remark" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="editdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleMertotal">保存</el-button>
        </span>
        </template>
      </el-dialog>

        <el-dialog title="修改收货人信息"
                   v-model="receiverDialogVisible"
                   width="40%">
            <el-form :model="receiverInfo"
                     ref="receiverInfoForm"
                     label-width="150px">
                <el-form-item label="收货人姓名：">
                    <el-input v-model="receiverInfo.consignee" style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="手机号码：">
                    <el-input v-model="receiverInfo.phone" style="width: 200px">
                    </el-input>
                </el-form-item>
                <el-form-item label="邮政编码：">
                    <el-input v-model="receiverInfo.zipcode" style="width: 200px">
                    </el-input>
                </el-form-item>
                <el-form-item label="所在区域：">
                    <el-cascader
                            v-model="selectedOptions"
                            :options="options"
                            @change="handleChange"
                            clearable
                            style="width: 300px;"
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="详细地址：">
                    <el-input v-model="receiverInfo.streetAddress" type="textarea" rows="3">
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" style="margin-left: 40%">
                 <el-button @click="receiverDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleUpdateReceiverInfo">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog title="新增商品列表"
                   v-model="merDialogVisible"
                   width="80%">
            <div class="table-layout">

              <div style="margin-bottom: 20px">
                <span style="margin-right: 10px">选择配送地址：</span>
                <el-select
                    v-model="selectedAddress"
                    placeholder="请选择地址"
                    @change="filterMerchandise"
                >
                  <el-option
                      v-for="item in addressOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </div>

                <el-table :data="filteredMeraddlist" style="width: 100%;margin-top: 20px" border>
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column prop="productId" label="商品编码" width="100"></el-table-column>
                    <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
                    <el-table-column prop="source" label="商品来源" width="110"></el-table-column>
                    <el-table-column prop="specification" label="商品规格" width="110"></el-table-column>
                    <el-table-column prop="price" label="单价" width="100"></el-table-column>
                    <el-table-column label="销售数量" align="center">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.orderNum" @change="updateMertotal(scope.row)"/>
                        </template>
                    </el-table-column>
                   <el-table-column label="小计" width="100">
                     <template #default="scope">
                       {{ scope.row.mertotal }}
                    </template>
                  </el-table-column>
                </el-table>

              <pagination
                  v-show="total>0"
                  :total="total"
                  v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize"
                  @pagination="getList"
                  style="width: 10%; height: 50%"
              />



              <span slot="footer" class="dialog-footer" style="margin-left: 45% ; margin-top: 20px">
                 <el-button @click="merDialogVisible = false">取 消</el-button>
                 <el-button type="primary" @click="handleAddMerList">确 定</el-button>
             </span>


            </div>

        </el-dialog>
        <el-dialog title="修改基本信息"
                   v-model="baseDialogVisible"
                   width="40%">
            <el-form :model="baseInfo"
                     ref="receiverInfoForm"
                     label-width="150px">
                <el-form-item  label="订单编码" >
                    <el-input v-model="baseInfo.orderId" placeholder="请修改订单编码" style="width: 220px" disabled/>
                </el-form-item>
                <el-form-item label="订单状态" >
                    <el-select  v-model="baseInfo.orderStatus" placeholder="请选择订单状态" style="width: 220px" disabled>
                        <el-option
                                v-for="dict in order_status.order_status"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="订单日期">
                    <el-date-picker clearable
                                    v-model="baseInfo.orderDate"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="请选择订单日期"
                                    style="width: 220px" disabled>
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="业务类型" >
                    <el-select v-model="baseInfo.businessType" placeholder="请选择业务类型" style="width: 220px" disabled>
                        <el-option
                                v-for="dict in business_type.business_type"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>

              <el-form-item label="客户名称" prop="customerId">
                <el-select v-model="baseInfo.customerId" placeholder="请选择客户名称" style="width: 220px" disabled>
                  <el-option
                      v-for="user in customerlist"
                      :key="user.customerId"
                      :label="user.customerName"
                      :value="user.customerId"
                  ></el-option>
                </el-select>
              </el-form-item>

                <el-form-item label="付款方式" >
                    <el-select v-model="baseInfo.paymentMethod" placeholder="请选择付款方式" style="width: 220px" disabled>
                        <el-option
                                v-for="dict in payment_meth.payment_meth"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="配送方式" >
                    <el-input v-model="baseInfo.transportMode" type="textarea" placeholder="请输入内容" disabled/>
                </el-form-item>
                <el-form-item label="物流单号" >
                    <el-input v-model="baseInfo.logisticsNumber" type="textarea" placeholder="请输入内容" disabled/>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" style="margin-left: 40%">
        <el-button @click="baseDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleBaseInfo">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
    import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/order.js";
    import {getCustomerList, listInfo,getInfo, updateInfo} from "@/api/system/info.js";
    import {getData,getDicts} from "@/api/system/dict/data.js"
    import {getCustomer, updateAddr,getCustomerAddr} from "../../api/system/addr.js";
    import {getDetail,addDetail,updateDetail,delSalesDetail} from "@/api/system/detail.js";
    import {getCategoryByType, getMerInfo, listMerInfo} from "../../api/system/merinfo.js";
    import { useDict } from '@/utils/dict.js'
    import * as areaData from 'element-china-area-data';
    import { listTrace, getTrace, delTrace, addTrace, updateTrace } from "@/api/system/trace.js";
    import ImageUpload from "@/components/ImageUpload/index.vue";
    import {addMessage} from "@/api/system/message.js";
    import {useDrawerStore} from "@/store/drawerStore.js";
    import useDictStore from "@/store/modules/dict.js";
    import {getUserProfile} from "@/api/system/user.js";
    import {sendToUser} from "@/api/system/message.js";
    import {stringify} from "zrender/lib/tool/color.js";

    const drawerStore = useDrawerStore();
    const dictStore = useDictStore();

    function cloneDeep(value, hash = new WeakMap()) {

      if (value === null || typeof value !== 'object') {
        return value;
      }

      if (hash.has(value)) {
        return hash.get(value);
      }


      if (value instanceof Date) {
        const dateCopy = new Date(value);
        hash.set(value, dateCopy);
        return dateCopy;
      }


      if (value instanceof RegExp) {
        const regExpCopy = new RegExp(value);
        hash.set(value, regExpCopy);
        return regExpCopy;
      }


      if (Array.isArray(value)) {
        const arrayCopy = [];
        hash.set(value, arrayCopy);
        value.forEach((item, index) => {
          arrayCopy[index] = cloneDeep(item, hash);
        });
        return arrayCopy;
      }


      const objectCopy = {};
      hash.set(value, objectCopy);

      for (let key in value) {
        if (value.hasOwnProperty(key)) {
          objectCopy[key] = cloneDeep(value[key], hash);
        }
      }

      return objectCopy;
    }

    export default {


        name: "orderEdit",
        components: {ImageUpload},

        data() {
            return {

              pendingChanges: [],

              addressOptions: [], // 地址选择器选项
              selectedAddress: null, // 当前选中的地址
              filteredMeraddlist: [], // 过滤后的商品列表

              role: "",
              //分页查询参数
              queryParams: {
                pageNum: 1,
                pageSize: 10,
              },
              orderNum: {}, // 商品数量映射
              total: null, // 总记录数
              mertotal: {}, // 商品小计映射

              // 字典数据
              order_status: useDict('order_status'),
              payment_meth: useDict('payment_meth'),
              business_type: useDict('business_type'),
              orderStatus:{},
              paymentMeth:{},
              businessType:{},

              // 地址选择器默认选中项
              selectedOptions: ['13', '1301', '130104'],
              options: areaData.regionData,
              defaultSelectedNames:[],

              // 订单信息
              order: {
                invoiceInfo: []
              },
              orderTrace: {},
              payment: {},
              dictType: {},
              business: {},
              customerAddr: {},
              customerlist: [],
              merlist: [],
              merdetail: {},
              meraddlist: [], // 新增商品列表
              originalMerAddList: [], // 新增商品列表的原始副本
              isInitialized: false, // 初始化状态标识
              initialInvoice: null,  // 初始发票快照

              // 富化订单详情列表
              enrichedOrderDetails: [],

              // 对话框显示状态
              isEdited:false,
              baseDialogVisible: false,
              receiverDialogVisible: false,
              merDialogVisible: false,
              editdialogVisible: false,

              // 基本信息表单
              baseInfo: {
                orderId: '',
                orderStatus: '',
                orderDate: '',
                businessType: '',
                customerId: null,
                paymentMethod: '',
                transportMode: '',
                logisticsNumber: ''
              },
              originalBaseInfo: {}, // 基本信息表单的原始副本

              // 收货人信息表单
              receiverInfo: {
                consignee: '',
                phone: '',
                zipcode: '',
                streetAddress: ''
              },

              // 客户信息
              customer: {
                customerId: null,
                customerName: '',
                businessType: '',
                customerEmail: '',
                contactInfo: '',
                realNameId: ''
              },

              // 修改商品详情表单
              form: {
                addressId:'',
                customerAddr: '',
                productId: '',
                merchandiseName: '',
                merchandiseCategory: '',
                manufacturer: '',
                productPrice: 0,
                productSalesQuantity: 0,
                subtotal: 0,
                totalAmount: 0,
                warehouseCode: '',
                remark: ''
              },
              originalForm: {}, // 修改商品详情表单的原始副本

              // 步骤和状态
              steps: [
                { title: "待确认" },
                { title: "待支付" },
                { title: "已支付" },
                { title: "待发货" },
                { title: "已发货" },
                { title: "运输中" },
                { title: "派送中" },
                { title: "待签收" },
                { title: "已签收" }
              ],
              status: ["待确认", "待支付", "已支付", "待发货", "已发货", "运输中", "派送中", "待签收", "已签收"],

              // 字段标签映射
              fieldLabels: {
                orderId: '订单编号',
                orderStatus: '订单状态',
                orderDate: '订单日期',
                businessType: '业务类型',
                customerId: '客户名称',
                paymentMethod: '付款方式',
                transportMode: '配送方式',
                logisticsNumber: '物流单号',
                consignee: '收货人',
                phone: '手机号码',
                zipcode: '邮政编码',
                streetAddress: '详细地址',
                state: '省份',
                city: '城市',
                district: '区县',
                productId: '商品编号',
                merchandiseName: '商品名称',
                merchandiseCategory: '商品类别',
                manufacturer: '生产厂商',
                productPrice: '商品价格',
                productSalesQuantity: '商品数量',
                subtotal: '小计',
                totalAmount: '总金额',
                warehouseCode: '仓库编号',
                remark: '备注'
            }
          }
        },


        async mounted() {
          this.id = this.list = this.$route.query.id;
          this.role = await this.getUserRole();
          console.log('order role',this.role)
          this.loadOrderAndCustomer();
          this.loadDict()

        },

      watch: {
        selectedAddress(newVal) {
          this.filterMerchandise();
          this.queryParams.pageNum = 1; // 重置分页
          this.getMerAddListInfo();
        },
        // 'order.invoiceInfo': {
        //   handler(newVal, oldVal) {
        //
        //     if(!oldVal){
        //       return
        //     }
        //
        //     if (newVal && newVal.length > 0 && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
        //       this.$confirm('检测到发票信息变更，是否保存？', '提示', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning'
        //       }).then(() => {
        //         this.handleAutoSaveInvoice();
        //       }).catch(() => {
        //         this.order.invoiceInfo = oldVal; // 取消时恢复原值
        //       });
        //     }
        //   },
        //   deep: true
        // }
      },


      methods: {

        async handleAutoSaveInvoice() {
          try {
            const response = await updateOrder({
              orderId: this.order.orderId,
              invoiceInfo: this.order.invoiceInfo
            });
            this.$message.success('发票信息已自动保存');
            this.loadOrderAndCustomer(); // 刷新最新数据
          } catch (error) {
            this.$message.error('自动保存失败: ' + (error.message || '未知错误'));
            console.error('发票保存错误:', error);
          }
        },

        filterMerchandise() {
          if (!this.selectedAddress) return;

          // 获取当前地址已存在的商品ID集合
          const existingProducts = new Set(
              this.enrichedOrderDetails
                  .filter(item => item.addressId === this.selectedAddress)
                  .map(item => item.productId)
          );

          this.filteredMeraddlist = this.meraddlist.filter(item => {
            // 显示满足以下条件的商品：
            // 1. 不在当前地址已选商品中
            // 2. 属于当前选中地址（根据数据结构调整）
            return !existingProducts.has(item.productId);
          });

          console.log('filteredMeraddlist',this.filteredMeraddlist)
        },

        async getCustomerAddresses() {
          try {
            const response = await getCustomer(this.order.customerId);
            this.addressOptions = response.data.map(addr => ({
              value: addr.addressId,
              label: `${addr.state} ${addr.city} ${addr.district} ${addr.streetAddress}`
            }));

            // 设置默认选中第一个地址
            if (this.addressOptions.length > 0) {
              this.selectedAddress = this.addressOptions[0].value;
            }
          } catch (error) {
            console.error('获取地址失败:', error);
          }
        },

        async getUserRole(){
          try {
            const response = await getUserProfile();
            console.log('userinfo response:', response.data.roles[0].roleName);
            return response.data.roles[0].roleName;
          } catch (error) {
            console.error('获取用户信息失败:', error);
          }
        } ,

        // =================== 修改订单商品操作 ===================

        updateEditMertotal(form){
          form.totalAmount = form.price * form.productSalesQuantity
        },

        updateMertotal(row) {
          console.log(row)
          row.mertotal = row.price * row.orderNum;
        },


        loadDict(){

          getDicts("payment_meth").then(response =>{
            this.paymentMeth =response.data
            console.log(this.paymentMeth)
          })

          getDicts("order_status").then(response =>{
            this.orderStatus =response.data
            console.log(this.orderStatus)
          })

          getDicts("business_type").then(response =>{
            this.businessType =response.data
            console.log(this.businessType)
          })

        },

        handleAddMer(){
          this.merDialogVisible = true;
          this.getCustomerAddresses().then(() => {
            this.filterMerchandise();
          });
        },

        handleUpdate(row){
          const matchedDetail = this.enrichedOrderDetails.find(
              item => item.productId === row.productId
          );

          Object.assign(this.form, row, {
            addressId: matchedDetail?.addressId || '无地址信息',
            customerAddr: matchedDetail?.customerAddr || '无地址信息'
          });

          this.originalForm = cloneDeep(this.form);
          this.editdialogVisible = true;
        },

        handleDelete(row){
          this.$confirm('确定删除该商品吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delSalesDetail(row.orderId, row.productId).then(() => {
              this.$message.success("删除成功");
              this.loadOrderAndCustomer();
            });
          });

        },

        // =================== 订单操作 ===================
        /**
         * 加载订单及客户信息
         */
        loadOrderAndCustomer() {
          getOrder(this.id).then(response => {
            this.order = response.data;
            this.getpayDict();
            this.getDictsType();
            this.getBusiness();
            this.getCustomerAddr();
            this.loadDefaultSelection();
            this.getMerList();
            this.getMerDetail();
            this.getTrace();
            this.listCustomerInfo();
            this.getCustomerAddresses();
            return this.getCustomer();
          }).then(() => {
          })
              .catch(error => {
                console.error('获取订单或客户信息失败:', error);
              });
        },

        /**
         * 获取客户列表信息
         */
        listCustomerInfo() {
          listInfo().then(response => {
            this.customerlist = response.rows;
          });
        },

        /**
         * 获取客户详细信息
         */
        getCustomer() {
          if (!this.order.customerId) {
            console.warn('没有有效的 customerId');
            return Promise.resolve();
          }
          return getInfo(this.order.customerId).then(response => {
            this.customer = response.data;
          }).catch(error => {
            console.error('获取客户信息失败:', error);
            throw error;
          });
        },

        /**
         * 获取订单追踪信息
         */
        getTrace() {
          getTrace(this.order.orderId).then(response => {
            this.orderTrace = response.data;
          });
        },

        /**
         * 显示关闭订单对话框，并处理订单取消逻辑
         */
        showCloseOrderDialog() {
          this.$confirm('是否要取消该订单', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delOrder(this.order.orderId).then(response => {
              this.$message.success('订单取消成功');
              this.$tab.closeOpenPage(this.$route);
              this.$router.go(-1);
              let processData;
              if(this.role === '平台运营商'){
                 processData = {
                  userId: this.order.customerId,
                  readStatus: 0,
                  auditStatus: 0,
                  content: "您的订单已取消",
                  title: "订单取消通知",
                  time: new Date().getTime()
                };
              }else{
                 processData = {
                  userId: 3,
                  status: 0,
                  content: "您的订单已取消",
                  title: "订单取消通知",
                  time: new Date().getTime()
                };
              }


              addMessage(processData).then(response => {
                this.$message.success('订单变更记录添加成功');
                drawerStore.setRefreshMessages(true);
                this.loadOrderAndCustomer(); // 刷新订单信息
              }).catch(error => {
                this.$message.error('订单变更记录添加失败');
                console.error('订单变更记录添加失败:', error);
              });
            }).catch(error => {
              this.$message.error('订单取消失败');
              console.error('取消订单失败:', error);
            });
          });
        },

        /**
         * 显示确认订单对话框，并处理订单确认逻辑
         */
        showSureOrderDialog() {
          this.$confirm('是否要确认该订单', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const updatedOrderInfo = {
              orderId: this.order.orderId,
              orderStatus: '2' // 将订单状态修改为“待支付”
            };
            updateOrder(updatedOrderInfo).then(response => {
              this.$message.success('订单确认成功');
              let processData;
              if(this.role === '平台运营商'){
                processData = {
                  userId: this.order.customerId,
                  readStatus: 0,
                  auditStatus: 0,
                  content: "您的订单已确认",
                  title: "订单确认通知",
                  time: new Date().getTime()
                };
              }else{
                processData = {
                  userId: 3,
                  readStatus: 0,
                  auditStatus: 0,
                  content: "您的订单已确认",
                  title: "订单确认通知",
                  time: new Date().getTime()
                };
              }


              if (this.order.orderStatus === '2') {

              }

              addMessage(processData).then(response => {
                this.$message.success('订单变更记录添加成功');
                drawerStore.setRefreshMessages(true);
                this.$tab.closeOpenPage(this.$route);
                this.$router.go(-1);
              }).catch(error => {
                this.$message.error('订单变更记录添加失败');
                console.error('订单变更记录添加失败:', error);
              });
            }).catch(error => {
              this.$message.error('订单确认失败');
              console.error('确认订单失败:', error);
            });
          });
        },

        // =================== 对话框控制 ===================
        /**
         * 显示修改基本信息对话框
         */
        showUpdateBaseDialog() {
          this.baseDialogVisible = true;
          this.baseInfo = {
            orderId: this.order.orderId,
            orderStatus: this.order.orderStatus,
            orderDate: this.order.orderDate,
            businessType: this.order.businessType,
            customerId: this.customer.customerId,
            paymentMethod: this.order.paymentMethod,
            transportMode: this.orderTrace.transportMode,
            logisticsNumber: this.orderTrace.logisticsNumber,
          };
          this.originalBaseInfo = cloneDeep(this.baseInfo);
        },

        /**
         * 显示修改收货人信息对话框
         */
        showUpdateReceiverDialog() {
          this.receiverDialogVisible = true;
          this.receiverInfo = {
            orderId: this.order.orderId,
            consignee: this.customerAddr.consignee,
            phone: this.customerAddr.phone,
            zipcode: this.customerAddr.zipcode,
            streetAddress: this.customerAddr.streetAddress,
            state: this.customerAddr.state,
            city: this.customerAddr.city,
            district: this.customerAddr.district,
            country: this.customerAddr.country,
            orderStatus: this.order.orderStatus
          };
          this.selectedOptions= this.namesToCodes([this.customerAddr.state, this.customerAddr.city, this.customerAddr.district])
          this.originalReceiverInfo = cloneDeep(this.receiverInfo);
          console.log('this.originalReceiverInfo',this.originalReceiverInfo)
        },

        // =================== 表单处理 ===================
        /**
         * 处理基本信息保存
         */
        handleBaseInfo() {
          this.$confirm('确定修改订单信息吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const changes = this.getChangedFields(this.originalBaseInfo, this.baseInfo);
            if (Object.keys(changes).length === 0) {
              this.$message.info("未对基本信息进行任何修改");
              return;
            }
            this.editBaseInfo = {
              orderId: this.baseInfo.orderId,
              orderStatus: this.baseInfo.orderStatus,
              orderDate: this.baseInfo.orderDate,
              businessType: this.baseInfo.businessType,
              customerId: this.baseInfo.customerId,
              paymentMethod: this.baseInfo.paymentMethod,
            };
            updateOrder(this.editBaseInfo).then(response => {
              this.remarkChanges(changes);
              this.$message.success('订单信息更新成功');
              this.baseDialogVisible = false;
              this.loadOrderAndCustomer(); // 刷新订单信息
            }).catch(error => {
              this.$message.error('订单信息更新失败');
              console.error('更新订单信息失败:', error);
            });
          });
        },

        /**
         * 处理收货人信息保存
         */
        handleUpdateReceiverInfo() {
          const processData = {
            addressId: this.form.addressId,
            customerId: this.order.customerId,
            consignee: this.originalReceiverInfo.consignee,
            phone: this.originalReceiverInfo.phone,
            zipcode: this.originalReceiverInfo.zipcode,
            streetAddress: this.originalReceiverInfo.streetAddress,
            state: this.originalReceiverInfo.state,
            city: this.originalReceiverInfo.city,
            district: this.originalReceiverInfo.district,
          };
          const updatedReceiverInfo = {
            addressId: this.form.addressId,
            customerId: this.order.customerId,
            consignee: this.receiverInfo.consignee,
            phone: this.receiverInfo.phone,
            zipcode: this.receiverInfo.zipcode,
            streetAddress: this.receiverInfo.streetAddress,
            state: this.codeToText(this.selectedOptions[0]),
            city: this.codeToText(this.selectedOptions[1]),
            district: this.codeToText(this.selectedOptions[2])
          };
          const changes = this.getChangedFields(processData, updatedReceiverInfo);
          if (Object.keys(changes).length === 0) {
            this.$message.info("未对收货人信息进行任何修改");
            return;
          }
          this.$confirm('是否要修改收货人信息', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.remarkChanges(changes)
            const processOrder = {
              orderId: this.order.orderId,
              orderStatus: 1,
            }
            updateOrder(processOrder).then(response =>{
              this.receiverDialogVisible = false
              this.loadOrderAndCustomer()
            })

            if(this.order.orderStatus === '1'){
              updateAddr(updatedReceiverInfo).then(response => {
                this.$message.success('收货人信息更新成功');
                this.receiverDialogVisible = false; // 关闭对话框
                this.loadOrderAndCustomer(); // 刷新订单信息
              }).catch(error => {
                this.$message.error('收货人信息更新失败');
                console.error('更新收货人信息失败:', error);
              });
            }


          });
        },

        /**
         * 新增商品列表项
         */
        // handleAddMerList() {
        //   this.isEdited = true
        //   this.$confirm('确定添加吗?', '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning'
        //   }).then(() => {
        //     const orderDetailData = this.meraddlist
        //         .filter(item => item.orderNum > 0)
        //         .map(item => ({
        //           addressId:this.selectedAddress,
        //           orderId: this.order.orderId,
        //           productId: item.merchandiseId,
        //           warehouseCode: "warehouseCode",
        //           subtotal: parseFloat(item.subtotal).toFixed(2),
        //           productSalesQuantity: item.orderNum,
        //           discount: parseFloat(0).toFixed(2), // 如果有折扣，则传递折扣值
        //           totalAmount: (parseFloat(item.subtotal) * item.orderNum - parseFloat(0)).toFixed(2)
        //         }));
        //     const productNames = this.meraddlist
        //         .filter(item => item.orderNum > 0)
        //         .map(item => item.merchandiseName)
        //         .join(', ');
        //
        //     const processChange ={
        //
        //       details: orderDetailData,
        //       changes:`${this.order.orderId}号订单: 新增了商品：${productNames} 请注意查收`
        //
        //     }
        //
        //     let processData;
        //     if(this.role === "平台运营商"){
        //       processData ={
        //
        //         userId:this.order.customerId,
        //         orderId:this.order.orderId,
        //         readStatus: 0,
        //         auditStatus: 0,
        //         content:JSON.stringify(processChange),
        //         title:"订单变更通知",
        //         time: new Date().getTime()
        //       }
        //
        //     }else{
        //       processData ={
        //
        //         userId:3,
        //         orderId:this.order.orderId,
        //         readStatus: 0,
        //         auditStatus: 0,
        //         content:JSON.stringify(processChange),
        //         title:"订单变更通知",
        //         time: new Date().getTime()
        //       }
        //
        //     }
        //
        //
        //     console.log('processData',processData)
        //
        //
        //     if(this.order.orderStatus === '1'){
        //       Promise.all(orderDetailData.map(item => addDetail(item)))
        //           .then(() => {
        //             this.$message.success('订单详情添加成功');
        //             this.merDialogVisible = false; // 关闭对话框
        //             this.loadOrderAndCustomer(); // 刷新订单信息
        //           })
        //           .catch(error => {
        //             this.$message.error('订单详情添加失败');
        //             console.error('订单详情添加失败:', error);
        //           });
        //
        //     }else{
        //
        //       addMessage(processData).then(response => {
        //         this.$message.success('订单变更记录添加成功');
        //         const processOrder = {
        //           orderId: this.order.orderId,
        //           orderStatus: 1,
        //         }
        //         updateOrder(processOrder).then(response =>{
        //           this.merDialogVisible = false; // 关闭对话框
        //           this.loadOrderAndCustomer(); // 刷新订单信息
        //         })
        //       }).catch(error => {
        //         this.$message.error('订单变更记录添加失败');
        //         console.error('订单变更记录添加失败:', error);
        //       });
        //
        //
        //     }
        //
        //
        //
        //   });
        // },

        async handleAddMerList() {
          // 移除非关键代码...
          const changes = {
            type: 'add',
            addressId: this.selectedAddress,
            products: this.meraddlist
                .filter(item => item.orderNum > 0)
                .map(item => ({
                  id: item.merchandiseId,
                  name: item.merchandiseName,
                  subtotal: parseFloat(item.subtotal).toFixed(2),
                  quantity: item.orderNum
                }))
          };

          if (changes.products.length > 0 && this.order.orderStatus !== '1') {
            this.pendingChanges.push(changes);
            this.merDialogVisible = false;
            this.$message.success('变更已暂存，请继续操作或提交');
          }else {
              const orderDetailData = this.meraddlist
                  .filter(item => item.orderNum > 0)
                  .map(item => ({
                    addressId: this.selectedAddress,
                    orderId: this.order.orderId,
                    productId: item.merchandiseId,
                    warehouseCode: "warehouseCode",
                    subtotal: parseFloat(item.subtotal).toFixed(2),
                   productSalesQuantity: item.orderNum,
                  }))
              this.meraddlist.forEach(item => {
                addDetail(item).then(response => {
                });
              })
            this.$message.success('订单详情添加成功');
          }
        },

        handleMertotal() {
          // 移除非关键代码...
          const change = {
            type: 'modify',
            productId: this.form.productId,
            addressId: this.form.addressId,
            oldQuantity: this.originalForm.productSalesQuantity,
            newQuantity: this.form.productSalesQuantity
          };

          if(this.order.orderStatus !== '1'){

            this.pendingChanges.push(change);
            this.editdialogVisible = false;
            this.$message.success('修改已暂存，请继续操作或提交');
          }else{
            const process = {
              orderId: this.order.orderId,
              productId:this.form.productId,
              productSalesQuantity: this.form.productSalesQuantity,
              addressId: this.form.addressId,
              totalAmount: parseFloat(this.form.totalAmount).toFixed(2)
            }
            updateDetail(process).then(response => {
              this.$message.success('订单详情修改成功');
              this.editdialogVisible = false;
              this.loadOrderAndCustomer()
            })
          }

        },

        async submitAllChanges() {
          if (this.pendingChanges.length === 0) {
            this.$message.warning('没有待提交的变更');
            return;
          }


          try {
            // 生成友好中文描述
            const changeDescriptions = [];

            this.pendingChanges.forEach(change => {
              if (change.type === 'add') {
                // 获取地址完整信息
                const address = this.addressOptions.find(
                    a => a.value === change.addressId
                )?.label || '未知地址';

                // 生成商品信息描述
                const products = change.products.map(p =>
                    `${p.name}（数量：${p.quantity}）`
                ).join('，');

                changeDescriptions.push(
                    `在【${address}】新增商品：${products}`
                );
              }
              else if (change.type === 'modify') {
                // 获取商品信息（假设商品名称在变更记录中）
                const product = this.enrichedOrderDetails.find(
                    p => p.productId === change.productId
                );

                changeDescriptions.push(
                    `修改商品【${product?.merchandiseName || change.productId}】数量：` +
                    `${change.oldQuantity} → ${change.newQuantity}`
                );
              }
            });

            // 构建更友好的消息内容
            const message = {
              userId: this.role ==='平台运营商' ? this.order.customerId : 3,
              type: "notification",
              title: '订单变更申请',
              content: `订单 ${this.order.orderId} 有以下变更待审核：\n` +
                  changeDescriptions.map(d => `• ${d}`).join('\n') ,
              /*+
                  `\n提交时间：${new Date().toLocaleString()}`,*/
                orderId: this.order.orderId,
                changes: this.pendingChanges,
                timestamp: this.formatDateTime(new Date())
          };

            // 获取审核人ID（根据业务逻辑）
            const userId = this.role === '平台运营商' ?
                this.order.customerId : 3;

            await sendToUser(userId, message).then(res => {
              this.$message.success('变更申请已提交，等待审核');
              this.pendingChanges = [];
              this.loadOrderAndCustomer();
            });


          } catch (error) {
            this.$message.error(`提交失败：${error.message}`);
          }
        },

        formatDateTime(date) {
          return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')} ` +
              `${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}:${date.getSeconds().toString().padStart(2,'0')}`;
        },

        /**
         * 修改商品详情保存
         */
       /* handleMertotal() {
          this.isEdited = true
          console.log('originalForm',this.originalForm)
          console.log('form',this.form)
          const originalData = {
            orderId: this.originalForm.orderId,
            productId: this.originalForm.productId,
            productSalesQuantity: this.originalForm.productSalesQuantity,
            subtotal: this.originalForm.subtotal,
            totalAmount: this.originalForm.totalAmount,
          };
          const processData = {
            orderId: this.form.orderId,
            productId: this.form.productId,
            productSalesQuantity: this.form.productSalesQuantity,
            subtotal: this.form.subtotal,
            totalAmount: this.form.totalAmount,
          };
          // const changes = this.getChangedFields(originalData, processData);
          // if (Object.keys(changes).length === 0) {
          //   this.$message.warning("没有修改任何信息");
          //   this.editdialogVisible = false;
          //   return;
          // }

          const changes ={
            details: processData,
            changes:`${this.order.orderId}号订单: 修改了商品：${this.form.productId} 的数量为：${this.form.productSalesQuantity}`
          }

          let processChanges;
          if(this.role === "平台运营商"){
            processChanges = {
              userId: this.order.customerId,
              orderId: this.order.orderId,
              readStatus: 0,
              auditStatus:0,
              content: JSON.stringify(changes),
              title: "新增商品通知", // 修改标题为“新增商品通知”
              time: new Date().getTime()
            };
          }else{
            processChanges = {
              userId: 3,
              orderId: this.order.orderId,
              readStatus: 0,
              auditStatus:0,
              content: JSON.stringify(changes),
              title: "新增商品通知", // 修改标题为“新增商品通知”
              time: new Date().getTime()
            };
          }




          if(this.order.orderStatus === '1'){
            updateDetail(processData).then(response => {
              this.$message.success("修改成功");
              this.loadOrderAndCustomer();
              this.getMerAddListInfo();
              this.editdialogVisible = false;
            });
          }else{
            addMessage(processChanges).then(response => {
              this.$message.success('订单变更记录添加成功');
              const processOrder ={
                orderId: this.order.orderId,
                orderStatus: 1,
              }
              updateOrder(processOrder).then(response =>{
                this.loadOrderAndCustomer();
                this.getMerAddListInfo()// 刷新订单信息
                this.editdialogVisible = false; // 关闭对话框
              })
            }).catch(error => {
              this.$message.error('订单变更记录添加失败');
              console.error('订单变更记录添加失败:', error);
            });
          }


        },*/


        getOrderTotal(){

          if(this.isEdited){
            console.log('成功调用')

            let total = 0;
            this.enrichedOrderDetails.forEach(item => {
              total = total + parseFloat(item.totalAmount);
            })
            const processData = {
              orderId: this.order.orderId,
              orderTotal: total.toFixed(2),
            };
            updateOrder(processData).then(response => {
              console.log('成功调用函数，更新总金额',total)
              this.isEdited =false
              this.loadOrderAndCustomer()
            });
          }



        },

        // =================== 辅助工具 ===================


        formatStepStatus(value) {

          return parseInt(value)-1;
        },

        getDescription(index) {
          const activeIndex = this.formatStepStatus(this.order.orderStatus);

          return index <= activeIndex ? this.order.modifiedDate: '';
        },

        /**
         * 格式化货币金额
         */
        formatCurrency(value) {
          if (value == null) return '0.00'; // 处理 null 或 undefined
          return parseFloat(value).toFixed(2); // 格式化为两位小数
        },

        /**
         * 获取地址字符串
         */
        getAddr() {
          return [
            this.customerAddr.country,
            this.customerAddr.state,
            this.customerAddr.city,
            this.customerAddr.district,
            this.customerAddr.streetAddress
          ].filter(Boolean).join('-');
        },

        /**
         * 地址选择器改变事件处理
         */
        handleChange() {
          console.log(this.selectedOptions);
          this.codeToText(this.selectedOptions[0]);
          this.codeToText(this.selectedOptions[1]);
          this.codeToText(this.selectedOptions[2]);
        },

        /**
         * 返回上一页
         */
        handleBack() {
          this.$tab.closeOpenPage(this.$route);
          this.$router.go(-1);
        },

        /**
         * 获取字典数据
         */
        getDictsType() {
          getDicts("business_type").then(response => {
            this.dictType = response.data;
          }).catch(error => {
            console.error(error);
            throw error;
          });
        },

        /**
         * 获取业务类型数据
         */
        getBusiness() {
          getData(parseInt(this.order.businessType) + 108).then(response => {
            this.business = response.data;
          }).catch(error => {
            console.error(error);
            throw error;
          });
        },

        /**
         * 获取付款方式数据
         */
        getpayDict() {
          getData(parseInt(this.order.paymentMethod) + 111).then(response => {
            this.payment = response.data;
          }).catch(error => {
            console.error(error);
            throw error;
          });
        },

        /**
         * 获取客户地址信息
         */
        getCustomerAddr() {
          getCustomerAddr(this.order.customerId,this.order.addressId).then(response => {
            this.customerAddr = response.data;
          }).catch(error => {
            console.error(error);
            throw error;
          });
        },

        /**
         * 获取商品列表信息
         */
        getMerList() {
          getDetail(this.order.orderId).then(response => {
            this.merlist = response.data;
            console.log("mmmm", this.merlist);
            this.fetchAndEnrichOrderDetails();
            console.log("1111111", this.enrichedOrderDetails);
          }).catch(error => {
            console.error(error);
            throw error;
          });
        },

        /**
         * 获取商品详细信息
         */
        getMerDetail() {
          getMerInfo(1).then(response => {
            this.merdetail = response.data;
          }).catch(error => {
            console.error(error);
            throw error;
          });
        },

        /**
         * 丰富订单详情列表
         */

        async fetchAndEnrichOrderDetails() {
          try {
            const response = await getDetail(this.order.orderId);
            this.merlist = response.data;
            console.log("merlist", this.merlist);

            // 计算总金额
            const total = this.merlist.reduce((sum, item) => {
              return sum + (parseFloat(item.totalAmount) || 0);
            }, 0);
            this.order.orderTotal = total.toFixed(2);

            // 获取所有商品信息
            const productIds = [...new Set(this.merlist.map(item => item.productId))];
            const productPromises = productIds.map(productId =>
                getMerInfo(productId).then(response => response.data)
            );
            console.log("productIds", productIds);
            console.log("productPromises", productPromises);
            const productInfos = await Promise.all(productPromises);

            console.log("productInfos", productInfos);

            // 获取所有地址信息
            const addrPromises = this.merlist.map(item =>
                getCustomerAddr(this.order.customerId, item.addressId)
                    .then(response => ({
                      ...response.data,
                      addressId: item.addressId // 保留原始addressId
                    }))
            );

            const addrInfos = await Promise.all(addrPromises);

            // 创建映射表
            const productInfoMap = productInfos.reduce((acc, info) => {
              if (info && info.productId) {
                acc[info.productId] = info;
              }
              return acc;
            }, {});

            // 合并数据
            this.enrichedOrderDetails = this.merlist.map((item, index) => {
              const addr = addrInfos[index] || {};
              const productInfo = productInfoMap[item.productId] || {};
              console.log("productInfo", productInfo)
              return {
                ...item,
                productId: item.productId,
                productName: productInfo.productName,
                productCategory: productInfo.type,
                specification: productInfo.specification,
                source: productInfo.source,
                price: productInfo.price,
                addressId: item.addressId,
                customerAddr: `${addr.state || ''} ${addr.city || ''} ${addr.district || ''} ${addr.streetAddress || ''}`.trim(),
                subtotal: productInfo.price * item.productSalesQuantity
              };
            });

            console.log("enrichedOrderDetails", this.enrichedOrderDetails);
            this.enrichedOrderDetails.sort((a, b) =>
                a.customerAddr.localeCompare(b.customerAddr)
            );
            this.calculateSpans();
            this.getOrderTotal();
            this.getMerAddListInfo();
          } catch (error) {
            console.error('无法丰富订单详情：', error);
          }
        },

        calculateSpans() {
          const spans = [];
          let pos = 0;
          const map = new Map();

          // 按地址分组
          this.enrichedOrderDetails.forEach((item, index) => {
            const key = item.customerAddr;
            if (map.has(key)) {
              map.get(key).push(index);
            } else {
              map.set(key, [index]);
            }
          });

          // 生成span配置
          map.forEach((indexes) => {
            indexes.forEach((i, idx) => {
              spans[i] = idx === 0 ? [indexes.length, 1] : [0, 0];
            });
          });

          this.spanMap = spans;
        },

        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
          // 只在配送地址列合并
          if (columnIndex === 0) {  // 根据实际列索引调整
            return this.spanMap[rowIndex] || [1, 1];
          }
        },

        /**
         * 获取新增商品列表信息
         */
        getMerAddListInfo() {
          this.meraddlist = [];
          getCategoryByType('三级目录').then(response => {
            const processedData = response.data.map(item => ({
              ...item,
              orderNum: 0,
            }));


            this.meraddlist = processedData
            console.log("meraddlist", this.meraddlist);

            this.filterMerchandise();

            // processedData.forEach(item => {
            //   const isDuplicate = this.enrichedOrderDetails.some(detail => detail.merchandiseId === item.merchandiseId);
            //   if (!isDuplicate) {
            //     console.log('item', item);
            //     this.meraddlist.push(item);
            //   }
            // });
            // this.filteredMeraddlist = [...this.meraddlist];
            // this.originalMerAddList = cloneDeep(this.meraddlist);
            // console.log('meraddlist', this.meraddlist);
            this.total = response.total;
          }).catch(error => {
            console.log(error);
            throw error;
          });
        },

        /**
         * 获取默认选中地区信息
         */
        loadDefaultSelection() {
          this.defaultSelectedNames[0] = this.customerAddr.state;
          this.defaultSelectedNames[1] = this.customerAddr.city;
          this.defaultSelectedNames[2] = this.customerAddr.district;
          const codes = this.namesToCodes(this.defaultSelectedNames);
          const savedSelection = JSON.parse(localStorage.getItem('selectedArea')) || codes;
          this.selectedOptions = savedSelection;
        },

        /**
         * 将区域名称转换为编码
         */
        namesToCodes(names) {
          let codes = [];
          let currentData = areaData.regionData;
          names.forEach(name => {
            let found = false;
            for (let key in currentData) {
              if (currentData[key].label === name) {
                codes.push(currentData[key].value);
                if (currentData[key].children) {
                  currentData = currentData[key].children;
                  found = true;
                  break;
                } else {
                  found = true;
                  break;
                }
              }
            }
            if (!found) {
              console.warn(`Could not find the area with name: ${name}`);
              return [];
            }
          });
          return codes;
        },

        /**
         * 将区域编码转换为文本
         */
        codeToText(code) {
          const find = (data, code) => {
            for (let key in data) {
              if (data[key].value === code) {
                return data[key].label;
              }
              if (data[key].children) {
                const result = find(data[key].children, code);
                if (result) return result;
              }
            }
            return null;
          };
          return find(areaData.regionData, code);
        },

        /**
         * 更新订单备注信息
         */
        remarkChanges(changes) {

          if (this.order.orderStatus==='2'||this.order.orderStatus==='3'|| this.order.orderStatus==='4'){

            // const changeDetails = Object.keys(changes).map(key => {
            //   const label = this.fieldLabels[key] || key;
            //   return `${label}: 由 ${changes[key].oldValue} 变更为 ${changes[key].newValue}`;
            // }).join(', ');

            let processData;
            if (this.role === '平台运营商'){
              processData = {
                userId: this.order.customerId,
                readStatus: 0,
                auditStatus: 0,
                orderId:this.order.orderId,
                content: JSON.stringify(changes),
                title: "订单变更通知",
                time: new Date().getTime()
              };
            }else{
              processData = {
                userId: 3,
                readStatus: 0,
                auditStatus: 0,
                orderId:this.order.orderId,
                content: JSON.stringify(changes),
                title: "订单变更通知",
                time: new Date().getTime()
              };
            }


            addMessage(processData).then(response => {
              this.$message.success('订单变更记录添加成功');
              drawerStore.setRefreshMessages(true);
              this.loadOrderAndCustomer(); // 刷新订单信息
            }).catch(error => {
              this.$message.error('订单变更记录添加失败');
              console.error('订单变更记录添加失败:', error);
            });

          }


        },
        /**
         * 记录新增商品保存
         */
        remarkAddMer(changes){

          if(this.order.orderStatus==='2'||this.order.orderStatus==='3'|| this.order.orderStatus==='4'){

            const processData ={
              userId:this.order.customerId,
              orderId:this.order.orderId,
              readStatus: 0,
              auditStatus: 0,
              content:changes,
              title:"订单变更通知",
              time: new Date().getTime()
            }

            addMessage(processData).then(response => {
              this.$message.success('订单变更记录添加成功');
              drawerStore.setRefreshMessages(true);// 设置刷新标志
              console.log('drawerStore.refresh',drawerStore.refresh)
              this.loadOrderAndCustomer(); // 刷新订单信息
            }).catch(error => {
              this.$message.error('订单变更记录添加失败');
              console.error('订单变更记录添加失败:', error);
            });
          }

        },

        /**
         * 记录商品详情保存
         */
        remarkUpdateMer(changes){

          if (this.order.orderStatus==='2'||this.order.orderStatus==='3'|| this.order.orderStatus==='4'){

            const changeDetails = Object.keys(changes).map(key => {
              const label = this.fieldLabels[key] || key;
              return `${label}: 变更为 ${changes[key].newValue}`;
            }).join(', ');

            const processData ={
              userId:this.order.customerId,
              orderId:this.order.orderId,
              readStatus: 0,
              auditStatus: 0,
              content:this.order.orderId + "号订单: 商品： " + this.originalForm.merchandiseName+"发生了变更: " + changeDetails,
              title:"订单变更通知",
              time: new Date().getTime()
            }

            addMessage(processData).then(response => {
              this.$message.success('订单变更记录添加成功');
              drawerStore.setRefreshMessages(true);// 设置刷新标志
              console.log('drawerStore.refresh',drawerStore.refresh)
              this.loadOrderAndCustomer(); // 刷新订单信息
            }).catch(error => {
              this.$message.error('订单变更记录添加失败');
              console.error('订单变更记录添加失败:', error);
            });

          }


        },

        /**
         * 获取字段变化
         */

        transOrderStatus(key){
          return this.orderStatus[key -1].dictLabel
        },

        transPaymentMeth(key){
          return this.paymentMeth[key-1].dictLabel
        },

        transBusinessType(key){
          return this.businessType[key-1].dictLabel
        },

        getChangedFields(original, current) {
          const changes = {};
          for (let key in original) {
            if (original[key] !== current[key]) {
              if(key === 'orderStatus'){
                changes[key] = {
                  oldValue: this.transOrderStatus(original[key]),
                  newValue: this.transOrderStatus(current[key])
                };
              }else if (key === 'paymentMethod')
              {
                changes[key] = {
                  oldValue: this.transPaymentMeth(original[key]),
                  newValue: this.transPaymentMeth(current[key])
                };
              }else if (key === 'businessType')
              {
                changes[key] = {
                  oldValue: this.transBusinessType(original[key]),
                  newValue: this.transBusinessType(current[key])
                };
              }else if (key === 'customerId')
              {
                changes[key] = {
                  oldValue: this.customerlist[original[key]].customerName,
                  newValue: this.customerlist[current[key]].customerName
                };
              } else{
                changes[key] = {
                  oldValue: original[key],
                  newValue: current[key]
                };

              }
            }
          }
          return changes;
        }
      }






    }
</script>

<style scoped>
    .detail-container {
        width: 90%;
        padding: 20px 20px 20px 20px;
        margin: 20px auto;
    }

    .operate-container {
        background: #F2F6FC;
        height: 80px;
        margin: -20px -20px 0;
        line-height: 80px;
    }

    .operate-button-container {
        float: right;
        margin-right: 20px
    }

    .table-layout {
        margin-top: 20px;
        border-left: 1px solid #DCDFE6;
        border-top: 1px solid #DCDFE6;
    }

    .table-cell {
        height: 60px;
        line-height: 40px;
        border-right: 1px solid #DCDFE6;
        border-bottom: 1px solid #DCDFE6;
        padding: 10px;
        font-size: 14px;
        color: #606266;
        text-align: center;
        overflow: hidden;
    }

    .table-cell-title {
        border-right: 1px solid #DCDFE6;
        border-bottom: 1px solid #DCDFE6;
        padding: 10px;
        background: #F2F6FC;
        text-align: center;
        font-size: 14px;
        color: #303133;
    }
    .table-layout {
        padding-bottom: 20px;
    }

    .button-container {
        margin-top: 20px;
        text-align: center;
    }

    /* 移除原有浮动样式 */
    .operate-button-container {
      float: none;
    }

    /* 新增按钮组样式 */
    .button-group {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10px;
    }

    .button-group > div {
      display: flex;
      gap: 10px;
      justify-content: center;
      width: 100%;
    }

</style>